// // 生成笛卡尔积
// export function generateCartesian(sales) {
//   // 生成属性二维数组
//   const arr = []
//   sales.forEach(sale => {
//     arr.push(sale.attrValue)
//   })
//
//   if (!Array.isArray(arr) || arr.length === 0) {
//     return []
//   }
//
//   function recursiveCartesian(arr, index) {
//     if (index === arr.length - 1) {
//       // [3,4] => [[3],[4]]
//       return arr[index].map(item => [item])
//     }
//
//     const result = []
//     const subProduct = recursiveCartesian(arr, index + 1)
//
//     /*
//       [[1,2],[3,4]]
//
//       [1,3]
//       [1,4]
//       [2,3]
//       [2,4]
//      */
//     for (const item of arr[index]) {
//       for (const subArr of subProduct) {
//         result.push([item, ...subArr])
//       }
//     }
//
//     return result
//   }
//
//   return recursiveCartesian(arr, 0)
// }


/**
 * 生成笛卡尔乘积
 *
 * @param sales   ===> [
 *                        {attrId: 1, attrValue: ['黑色','白色']},
 *                        {attrId: 2, attrValue: ['128GB','256GB']}
 *                     ]
 *
 * @returns {*[]|*} ===> [
 *                          [{attrId: 1, attrName: '黑色'},{attrId: 2, attrName: '128GB'}]
 *                          [{attrId: 1, attrName: '黑色'},{attrId: 2, attrName: '256GB'}]
 *                          [{attrId: 1, attrName: '白色'},{attrId: 2, attrName: '128GB'}]
 *                          [{attrId: 1, attrName: '白色'},{attrId: 2, attrName: '256GB'}]
 *                       ]
 */

const generateCartesian = (sales) => {

  if (!Array.isArray(sales) || sales.length === 0) {
    return []
  }

  /*
    [[1,2],[3,4]]
    sales = [
              {attrId: 1, attrValue: ['黑色','白色']},
              {attrId: 2, attrValue: ['128GB','256GB']}
            ]
   */

  function recursiveCartesian(sales, index) {
    if (index === sales.length - 1) {
      // ['黑色','白色'] => [['黑色'],['白色']]
      // {attrId: 1, attrValue: ['黑色','白色']} => [{attrId: 1, attrName: '黑色'},{attrId: 1, attrName: '白色'}]
      return sales[index].attrValue.map(item => {
        return [{
          attrId: sales[index].attrId,
          attrName: item
        }]
      })
    }

    const result = []
    const subAttrs = recursiveCartesian(sales, index + 1)

    /*
      [[1,2],[3,4]]

      [
        [1,3],
        [1,4],
        [2,3],
        [2,4]
      ]
     */

    for (let i = 0; i < sales[index].attrValue.length; i++) {
      for (const subAttr of subAttrs) {
        const row = [{ attrId: sales[index].attrId, attrName: sales[index].attrValue[i] }, ...subAttr]
        // row = [{attrId: 1, attrName: '黑色'}, {attrId: 1, attrName: '128GB'}]
        result.push(row)
      }
    }

    return result
  }

  return recursiveCartesian(sales, 0)
}

export { generateCartesian }
